package com.laoxu.java.collection;

import java.util.*;

/**
 * @author laoxu
 * @create 2018-02-04
 **/
public class CollectionsDemo {
    public static void main(String[] args) {

        //1. 操作List
        operateList();
        //2. 查找替换
        findReplace();
        //3. 同步控制
        syncControl();
        //4. 设置不可变（只读）集合
        setReadOnly();
    }

    private static void operateList(){
        ArrayList nums =  new ArrayList();
        nums.add(8);
        nums.add(-3);
        nums.add(2);
        nums.add(9);
        nums.add(-2);
        System.out.println(nums);
        Collections.reverse(nums);
        System.out.println(nums);
        Collections.sort(nums);
        System.out.println(nums);
        Collections.shuffle(nums);
        System.out.println(nums);
        //下面只是为了演示定制排序的用法，将int类型转成string进行比较
        Collections.sort(nums, new Comparator() {

            @Override
            public int compare(Object o1, Object o2) {
                String s1 = String.valueOf(o1);
                String s2 = String.valueOf(o2);
                return s1.compareTo(s2);
            }

        });
        System.out.println(nums);
    }

    private static void findReplace(){
        ArrayList num =  new ArrayList();
        num.add(3);
        num.add(-1);
        num.add(-5);
        num.add(10);
        System.out.println(num);
        System.out.println(Collections.max(num));
        System.out.println(Collections.min(num));
        Collections.replaceAll(num, -1, -7);
        System.out.println(Collections.frequency(num, 3));
        Collections.sort(num);
        System.out.println(Collections.binarySearch(num, -5));
    }

    private static void syncControl(){
        Collection c = Collections.synchronizedCollection(new ArrayList());
        List list = Collections.synchronizedList(new ArrayList());
        Set s = Collections.synchronizedSet(new HashSet());
        Map m = Collections.synchronizedMap(new HashMap());
    }

    private static void setReadOnly(){
        List lt = Collections.emptyList();
        Set st = Collections.singleton("avs");

        Map mp = new HashMap();
        mp.put("a",100);
        mp.put("b", 200);
        mp.put("c",150);
        Map readOnlyMap = Collections.unmodifiableMap(mp);

        //下面会报错
        lt.add(100);
        st.add("sdf");
        mp.put("d", 300);
    }
}
